﻿using System;

namespace ForgeCraft
{
    public class ObjectEntity : Entity
    {
        public ObjectItem Obj;

        public int timeInWorld = 0;

        public ObjectEntity(int x, int y, int z, ObjectItem obj, World world)
        {
            pos.x = (double)x + .5; pos.y = (double)y; pos.z = (double)z + .5;
            inWorld = world;
            Obj = obj;
            Spawned = true;

            base.Update();
            inWorld.objectsList.Add(this);
        }


        public void AddObject()
        {
            Creature newMob = new Creature();
            //newMob.pos = Server.world.spawn;
            newMob.mobType = 50;
            this.inWorld.SendToPlayersInRange(PacketWriter.MakeObjectSpawn(this), new Position(this.pos.x, this.pos.y, this.pos.z));
        }

        override public void Update()
        {
            //base.Update();

            ChunkBlock cb = inWorld.GetBlock((int)pos.x, (byte)(pos.y), (int)pos.z);

            Logger.Log("OPos: " + (int)pos.x + " " + (byte)(pos.y) + " " + (int)pos.z, LogType.Debug);

            if (cb.type < 1)
            {
                pos.y -= 0.20;
            }
           

            switch ((Block)cb.type)
            {
                case Block.Lava: Despawn(); return;
                case Block.StillLava: Despawn(); return;
            }

            // TODO: Add Velocity

            double dx = pos.x - lastpos.x, dy = pos.y - lastpos.y, dz = pos.z - lastpos.z;
            bool rotchanged = (pos.rotation != lastpos.rotation || pos.pitch != lastpos.pitch);

            lastpos.x = pos.x; lastpos.y = pos.y; lastpos.z = pos.z;
            lastpos.rotation = pos.rotation; lastpos.pitch = pos.pitch;

            if (dx != 0 || dy != 0 || dz != 0)
            {
                foreach (Player p in inWorld.playerList)
                {
                    if (inWorld.IsInPlayersChunk(p, pos))
                    {
                        p.UpdateEntity(this, dx, dy, dz, false, false, false);
                    }
                }
            }

            this.timeInWorld++;

            // TODO: Add a killspawn config to remove items after x * 5 seconds

            if (this.timeInWorld > 60) Despawn();

            if (((Object)Obj.Type == Object.FallingGravel || (Object)Obj.Type == Object.FallingSand) && this.timeInWorld > 10)
            {
                Despawn();
            }
        }

        override public void Despawn()
        {
            
            base.Despawn();
            inWorld.objectsList.Remove(this);
        }

        override public string ToString()
        {
            return "[Entity.Pickup " + id + ": " + Obj + "]";
        }
    }
}
